package vip.sweet.web.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import vip.sweet.common.enums.ResponseEnum;
import vip.sweet.common.exception.BaseException;
import vip.sweet.common.response.CommonResponse;

/**
 * @author ASUS
 * @Date 2025/7/13 17:23
 * @Descripition
 */
@Slf4j
@RestControllerAdvice// 全局异常处理
public class GlobalExceptionHandler {
    /**
     * 全局异常处理
     */
    @ExceptionHandler({BaseException.class})// 指定处理什么异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)// 设置状态码
    public CommonResponse handlerGlobalException(BaseException e) {
        log.error("全局异常处理:{}", e.getMessage());
        return CommonResponse.error(e.getResponseCodeEnum(), e);
    }
    @ExceptionHandler({AccessDeniedException.class})
    public CommonResponse handlerGlobalException() {
        return CommonResponse.error(ResponseEnum.UNAUTHORIZED);
    }
    /**
     * 处理BindException
     *
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResponse handlerBindException(BindException e) {
        log.error("请求异常：", e);
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        assert fieldError != null;
        String defaultMessage = fieldError.getDefaultMessage();

        return CommonResponse.error(ResponseEnum.BAD_REQUEST,defaultMessage);
    }

    /**
     * 处理Exception
     *
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public CommonResponse handlerException(Exception e) {
        log.error("请求异常：", e);
        return CommonResponse.error(ResponseEnum.ERROR, e);
    }
    /**
     * 处理Exception
     *
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public CommonResponse handlerUsernameNotFoundException(UsernameNotFoundException e) {
        log.error("请求异常：", e);
        return CommonResponse.error(ResponseEnum.ERROR, e);
    }
    @ExceptionHandler(NoResourceFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public CommonResponse handlerNoResourceFoundException(NoResourceFoundException e){
        log.error("请求异常：", e);
        return CommonResponse.error(ResponseEnum.NOT_FOUND, "请求资源不存在");
    }
}
